#include "databreader.h"

#include "databevent.h"
#include "datareader.h"
#include "startedevent.h"
#include "workdoneevent.h"

#include <random>
#include <memory>
#include <iostream>


#define COUNT_DATA 3;

namespace Lab1
{
    const std::chrono::milliseconds DataBReader::ResponseTime(5000);
    DataBReader::DataBReader( DataReader * reader )
        : reader( reader )
    {
    }

    void DataBReader::start( int iterations, bool errorEnd )
    {
        std::shared_ptr < Event > event ( new StartedEvent( Event::DEVICE_B ) );
        reader->getQueue().push( event );
        sleepThread();
        for( int i = 0; i < iterations; i++ )
        {
            read();
        }
        if( errorEnd )
        {
            event = std::shared_ptr < Event > ( new WorkDoneEvent( Event::DEVICE_B ) );
            reader->getQueue().push( event );
        }
    }

    void DataBReader::read()
    {
        std::vector < int > data;
        for(int i =0; i < 3;i++)
        {
            data.push_back( random(0,198));
        }
        std::shared_ptr < Event > event ( new DataBEvent( data ) );
        reader->getQueue().push(event);
        sleepThread();
    }

    void DataBReader::sleepThread()
    {
         std::this_thread::sleep_for(ResponseTime);
    }

    int  DataBReader::random(int min, int max)
    {
        return  min + (rand() % (int)(max - min + 1));
    }
}
